package cn.kimming.rpc.remoting.server;

import cn.kimming.rpc.remoting.transport.RpcRequest;
import cn.kimming.rpc.remoting.transport.RpcResponse;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.net.InetSocketAddress;
import java.util.concurrent.ExecutorService;

public class ServerHandler extends SimpleChannelInboundHandler<RpcRequest> {
    private static final Logger logger = LoggerFactory.getLogger(ServerHandler.class);

    private ServiceMap serviceMap;
    private ExecutorService bussinessPool;
    private String requestId;


    public ServerHandler(ServiceMap serviceMap, ExecutorService bussinessPool) {
        this.serviceMap = serviceMap;
        this.bussinessPool = bussinessPool;
    }

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, RpcRequest request) throws Exception {
        requestId = request.getRequestId();
        InetSocketAddress inetSocketAddress = (InetSocketAddress)ctx.channel().remoteAddress();
        logger.info("[my-rpc] server 收到来自主机{}:{} 请求服务{}, requestId: {}", inetSocketAddress.getHostString(), inetSocketAddress.getPort(), request.getInterfaceName() + ":" + request.getMethodName(), request.getRequestId());

        bussinessPool.submit(new ServiceCallTask(request, serviceMap, ctx.channel()));
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        cause.printStackTrace();
        RpcResponse response = new RpcResponse();
        response.setRequestId(requestId);
        response.setSuccess(false);
        response.setError(cause);
        ctx.writeAndFlush(response);
    }
}
